package com.cw.lang.common.framework.utils;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.cw.lang.common.utils.GsonUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;
import com.fasterxml.jackson.dataformat.javaprop.JavaPropsFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import com.fasterxml.jackson.dataformat.yaml.YAMLGenerator;
import com.fasterxml.jackson.dataformat.yaml.YAMLParser;

/**
 * yaml文件转properties和properties转yaml
 *
 * @create: 2019-03-27 12:16
 **/
public class YmlPropertiesTransferUtils {

    private static final String ENCODING = "utf-8";
    private static final Logger logger = LoggerFactory.getLogger(YmlPropertiesTransferUtils.class);

    /**
     * 从文件读取 yml2properties
     *
     * @param propertiesPath
     */
    public static boolean yml2properties(String yamlPath, String propertiesPath) throws IOException {
        JsonParser parser = null;
        JsonGenerator generator = null;
        YAMLFactory yamlFactory = new YAMLFactory();
        InputStreamReader inputStreamReader = null;
        FileInputStream inputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(yamlPath);
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName(ENCODING));
            parser = yamlFactory.createParser(inputStreamReader);
            JavaPropsFactory factory = new JavaPropsFactory();
            outputStream = new FileOutputStream(propertiesPath);
            outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName(ENCODING));
            generator = factory.createGenerator(outputStreamWriter);
            JsonToken token = parser.nextToken();
            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    generator.writeStartObject();
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    generator.writeFieldName(parser.getCurrentName());
                } else if (JsonToken.VALUE_STRING.equals(token)) {
                    generator.writeString(parser.getText());
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    generator.writeEndObject();
                }
                token = parser.nextToken();
            }
            logger.info("yml转properties成功，文件路径:{}", propertiesPath);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (parser != null) {
                parser.close();
            }
            if (generator != null) {
                generator.flush();
                generator.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }

    /**
     * 从文件读取 properties2yml
     *
     * @param propertiesPath
     */
    public static boolean properties2yml(String propertiesPath, String yamlPath) throws IOException {
        JsonParser parser = null;
        YAMLGenerator generator = null;
        JavaPropsFactory factory = new JavaPropsFactory();
        InputStreamReader inputStreamReader = null;
        FileInputStream inputStream = null;
        OutputStreamWriter outputStreamWriter = null;
        OutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(propertiesPath);
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName(ENCODING));
            parser = factory.createParser(inputStreamReader);
            YAMLFactory yamlFactory = new YAMLFactory();
            outputStream = new FileOutputStream(yamlPath);
            outputStreamWriter = new OutputStreamWriter(outputStream, Charset.forName(ENCODING));
            generator = yamlFactory.createGenerator(outputStreamWriter);

            JsonToken token = parser.nextToken();

            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    generator.writeStartObject();
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    generator.writeFieldName(parser.getCurrentName());
                } else if (JsonToken.VALUE_STRING.equals(token)) {
                    generator.writeString(parser.getText());
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    generator.writeEndObject();
                }
                token = parser.nextToken();
            }
            logger.info("properties转yml成功，文件路径:{}", yamlPath);
            return true;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (parser != null) {
                parser.close();
            }
            if (generator != null) {
                generator.flush();
                generator.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.flush();
                outputStream.close();
            }
        }
    }

    /**
     * 从文件读取 yml2properties
     *
     * @param ymlPath
     */
    public static List<String> yml2Properties(String ymlPath) throws IOException {
        final String DOT = ".";
        YAMLParser parser = null;
        List<String> lines = new LinkedList<>();
        InputStreamReader inputStreamReader = null;
        FileInputStream inputStream = null;
        try {
            YAMLFactory yamlFactory = new YAMLFactory();
            inputStream = new FileInputStream(ymlPath);
            inputStreamReader = new InputStreamReader(inputStream, Charset.forName(ENCODING));
            parser = yamlFactory.createParser(inputStreamReader);

            String key = "";
            String value;
            JsonToken token = parser.nextToken();
            while (token != null) {
                if (JsonToken.START_OBJECT.equals(token)) {
                    // do nothing
                } else if (JsonToken.FIELD_NAME.equals(token)) {
                    if (key.length() > 0) {
                        key = key + DOT;
                    }
                    key = key + parser.getCurrentName();

                    token = parser.nextToken();
                    if (JsonToken.START_OBJECT.equals(token)) {
                        continue;
                    }
                    value = parser.getText();
                    lines.add(key + "=" + value);

                    int dotOffset = key.lastIndexOf(DOT);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    }
                } else if (JsonToken.END_OBJECT.equals(token)) {
                    int dotOffset = key.lastIndexOf(DOT);
                    if (dotOffset > 0) {
                        key = key.substring(0, dotOffset);
                    } else {
                        key = "";
                        lines.add("");
                    }
                }
                token = parser.nextToken();
            }
            logger.info(GsonUtil.objectToJsonString(lines));
            return lines;
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            if (parser != null) {
                parser.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        properties2yml("D:\\chenw_project\\git_project\\自动化测试\\application.properties","D:\\chenw_project\\git_project\\自动化测试\\bootstrap.yml");
    }
}
